﻿using Microsoft.EntityFrameworkCore;
using SmartWMS.Common.Extensions;
using SmartWMS.Common.ResponseOutput;
using SmartWMS.Domain.Base;
using SmartWMS.Domain.SystemSet;
using SmartWMS.EntityFramework;
using SmartWMS.Server.Repository;
using SmartWMS.Server.SystemSets.MenuServices.Dto;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;

namespace SmartWMS.Server.SystemSets.MenuServices
{
    public class MenuService : IMenuService
    {
        private readonly IRepository<Permissions> _repository;
        private readonly SmartWMSContext _dbContext;
        public MenuService(IRepository<Permissions> repository, SmartWMSContext dbContext)
        {
            _repository = repository;
            _dbContext = dbContext;
        }
        /// <summary>
        /// 五表联查获取权限树
        /// </summary>
        /// <param name="key"></param>
        /// <returns></returns>
        public async Task<Response<List<MenuDto>>> GetmenuByIdAsync(KeyEntity key)
        {
            var list = (from a in _dbContext.Staff
                        join b in _dbContext.StaffRoles on a.Id equals b.StaffID
            join c in _dbContext.Role on b.RoleID equals c.Id
                        join d in _dbContext.RolePermissions on c.Id equals d.RoleID
                        join e in _dbContext.Permissions on d.PermissionsID equals e.Id
                        where a.Id == key.Id
                        select new MenuDto
                        {
                            id = e.Id,
                            pid = e.PID,
                            disable = e.IsDelete == true ? 1 : 0,
                            levelnum=e.levelnum,
                            icon = e.IconUrl,
                            name = e.Name,
                            path = e.Url,
                        }).Distinct().ToList();
            if (list.Count == 0)
            {
                return null;
            }
            else
            {
                var parentMenus = list.Where(m => m.pid == 0).ToList();
                var result = new List<MenuDto>();
                for (int i = 0; i < parentMenus.Count; i++)
                {
                    var treeNode = new MenuDto();
                    treeNode.id = parentMenus[i].id;
                    treeNode.pid = parentMenus[i].pid;
                    treeNode.disable = parentMenus[i].disable;
                    treeNode.levelnum= parentMenus[i].levelnum;
                    treeNode.icon = parentMenus[i].icon;
                    treeNode.name = parentMenus[i].name;
                    treeNode.path = parentMenus[i].path;
                    treeNode.children = GetLeftTree(list, treeNode.id);
                    result.Add(treeNode);
                }
                return Response<List<MenuDto>>.Ok(result);
            }
        }

        /// <summary>
        /// 递归获取权限子级
        /// </summary>
        /// <param name="permissions"></param>
        /// <param name="pId"></param>
        /// <returns></returns>
        public List<MenuDto> GetLeftTree(List<MenuDto> permissions, int pId)
        {
            var treeNodes = new List<MenuDto>();
            var tmpList = permissions.Where(m => m.pid == pId);
            if (!tmpList.Any()) return treeNodes;

            var list = tmpList.ToList();
            for (int i = 0; i < list.Count; i++)
            {
                var treeNode = new MenuDto();
                treeNode.id = list[i].id;
                treeNode.pid = list[i].pid;
                treeNode.disable = list[i].disable;
                treeNode.icon = list[i].icon;
                treeNode.levelnum = list[i].levelnum;
                treeNode.name = list[i].name;
                treeNode.path = list[i].path;
                treeNode.children = GetLeftTree(permissions, treeNode.id);
                treeNodes.Add(treeNode);
            }

            return treeNodes;
        }


        /// <summary>
        /// 添加权限树
        /// </summary>
        /// <param name="input"></param>
        /// <returns></returns>
        public async Task<Response<bool>> AddPermissionTreeAsync(MenuInput input)
        {
            var permissions = input.MapTo<Permissions>();
            //唯一验证
            var isExist = await _repository.GetListQuery().AnyAsync(m => m.Name == input.Name);

            if (isExist == true)
            {
                return Response<bool>.Fail("权限名称已存在");
            }
            else
            {
                var result = await _repository.InsertAsync(permissions);

                return Response<bool>.Ok(result > 0);
            }
        }

        /// <summary>
        /// 获取权限树
        /// </summary>
        /// <param name="pId">The p identifier.</param>
        /// <returns></returns>
        public Response<dynamic> GetPermissionTree(int pId)
        {
            // 子列表
            var list = _repository.GetListQuery().Where(m => m.PID == pId).ToList();
            // 转换格式为树型菜单
            var menuList = list.Select(m => new
            {
                id = m.Id,
                parentId = m.PID,
                name = m.Name,
                PUrl = m.Url,
                IconUrl = m.IconUrl,
                ISDelete = m.IsDelete,
                SortId = m.SortId,
                children = GetPermissionTree(m.Id).Data == null ? null : GetPermissionTree(m.Id).Data
            }).ToList();
            return Response<dynamic>.Ok(menuList);
        }

        /// <summary>
        /// 权限反填
        /// </summary>
        /// <param name="key"></param>
        /// <returns></returns>
        public async Task<Response<MenuInput>> GetPermissionByIdAsync(KeyEntity key)
        {
            var result = await _repository.GetEntityByIdAsync(key);
            return Response<MenuInput>.Ok(result.MapTo<MenuInput>());
        }

        /// <summary>
        /// 修改权限树
        /// </summary>
        /// <param name="input"></param>
        /// <returns></returns>
        public async Task<Response<bool>> UpdatePermissionTreeAsync(MenuInput input)
        {
            var permissions = input.MapTo<Permissions>();
            var result = await _repository.UpdateAsync(permissions);
            return result > 0 ? Response<bool>.Ok(result > 0) :
                Response<bool>.Fail(result > 0);
        }
        /// <summary>
        /// 获取全部权限
        /// </summary>
        /// <returns></returns>
        public async Task<Response<List<MenuInput>>> GetAllPermissionAsync()
        {
            var list = _repository.GetListQuery();
            var result = list.MapToList<MenuInput>();
            return Response<List<MenuInput>>.Ok(result);
        }

        public Task<Response<List<MenuInput>>> GetMenuByUserIdAsync(KeyEntity key)
        {
            throw new NotImplementedException();
        }

    }
}
